<template>
  <div class="container">
    <div class="app-container">
      <div class="left-container">
        <el-input :prefix-icon="Search" placeholder="请输入员工姓名搜索" v-model="pageParam.keyword" @input="valueChange"></el-input>
        <el-tree ref="deptTree" node-key="id" @current-change="selectNode" style="max-width: 600px" :data="DeptData" :props="defaultProps" default-expand-all highlight-current />
      </div>

      <div class="right-container">
        <!-- 按钮操作区域 -->
        <el-row type="flex" justify="end" class="operate-tools">
          <el-button size="small" type="primary" @click="addEmployeeClick">添加员工</el-button>
          <!-- <el-button v-permission="'add-employee'" size="mini" type="primary" @click="addEmployeeBtn"
            >添加员工</el-button
          > -->
          <el-button size="small">excel导入</el-button>
          <el-button size="small">excel导出</el-button>
        </el-row>
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto"></el-avatar>
              <span v-else class="username">头像</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center"></el-table-column>
          <el-table-column prop="mobile" label="手机号" align="center"></el-table-column>
          <el-table-column prop="workNumber" label="工号" align="center"></el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center" :formatter="formaStatus">
            <!-- <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1"> 正式</span>
              <span v-else-if="row.formOfEmployment === 2"> 非正式</span>
              <span v-else>无</span>
            </template> -->
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" align="center"></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" align="center"></el-table-column>
          <el-table-column label="操作" width="200px" align="center">
            <template v-slot="{ row }" class="btn">
              <el-button size="small" text type="primary" @click="router.push(`/main/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="small" text type="primary" @click="addRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除该行数据吗?" @confirm="conFirmDelBtn(row)" confirm-button-text="确认" cancel-button-text="取消">
                <template #reference>
                  <el-button size="small" text type="primary">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row justify="end">
          <el-pagination v-model:current-page="pageParam.page" v-model:page-size="pageParam.pagesize" :page-sizes="[5, 10, 20, 30]" size="default" layout="total, sizes, prev, pager, next, jumper" :total="tota" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-row>
      </div>
      <el-dialog v-model="RoleDialogVisible" title="分配角色" @close="closeBtn">
        <el-checkbox-group v-model="checkListRoleIds">
          <el-checkbox v-for="item in roleListData" :key="item.id" :value="item.id"> {{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeBtn">取消</el-button>
            <el-button type="primary" @click="assignRolesBtn"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { getDepartmentListApi } from "@/api/department";
import { getEmployeeListApi, deleteEmployeeApi, getEmployeeDetailApi } from "@/api/employee";
import { getEnabledRoleListApi, assignRolesApi } from "@/api/role/index.ts";
import { onMounted, reactive, ref, nextTick } from "vue";
import { tranListToTreeData } from "@/utils/index";
import { debounce, throttle } from "lodash";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";

const checkList = ref(["Value selected and disabled", "Value A"]);

const router = useRouter();
const route = useRoute();

const DeptData: Tree[] = reactive([]); // 部门数据
const employeeList = ref([]); // 员工列表数据
const pageParam = ref({
  page: 1,
  pagesize: 10,
  keyword: "", // 根据名字模糊查询
  departmentId: null, //部门id 默认为null 因为初始化的时候还没有选中节点 所以默认为空
});
const tota = ref(0); // 员工列表总条数
const deptTree = ref(); // 树组件的ref
const RoleDialogVisible = ref(false); // 控制角色对话框的显示隐藏
const roleListData = ref([]); // 角色列表数据
const currenId = ref(null); // 当前选中员工的id
const checkListRoleIds = ref([]); // 当前选中员工拥有的角色id列表

onMounted(() => {
  getDepartmentList();
  getEmployeeList();
});
interface Tree {
  label: string;
  children?: Tree[];
}
// 获取部门列表数据
const getDepartmentList = async () => {
  const res = tranListToTreeData(await getDepartmentListApi(), 0);
  DeptData.push(...res);
  pageParam.value.departmentId = res[0].id || null; // 默认选中第一个部门
  // 设置选中节点
  // 树组件渲染是异步的 等到更新完毕
  nextTick(() => {
    deptTree.value.setCurrentKey(pageParam.value.departmentId);
  });
  getEmployeeList();
};
// 配置树形控件的属性
const defaultProps = {
  children: "children",
  label: "name",
};
// 树组件切换部门节点 更新当前选中的部门id 查询第一页数据 并重新获取员工列表数据
const selectNode = (node) => {
  pageParam.value.departmentId = node.id; // 更新当前选中的部门id
  pageParam.value.page = 1; // 重置页码为第一页
  getEmployeeList(); // 重新获取员工列表数据
};
// 获取员工列表数据
const getEmployeeList = async () => {
  const { rows, total } = await getEmployeeListApi(pageParam.value);
  employeeList.value = rows;
  tota.value = total;
  // console.log(employeeList.value, "employeeList.value");
};

// 获取员工列表数据
// 格式化聘用形式
const formaStatus = (row) => {
  const MAP = {
    1: "正式",
    2: "非正式",
  };
  return MAP[row.formOfEmployment];
};

// 输入框搜索事件
const valueChange = debounce(() => {
  //设置页码为第一页
  pageParam.value.page = 1;
  // 重新获取员工列表数据
  getEmployeeList();
}, 300);

// 删除员工事件
const conFirmDelBtn = async (row) => {
  await deleteEmployeeApi(row.id);
  // 判断如果当前页只有一条数据 且不是第一页 则将页码减一 因为删除了一条数据 导致当前页没有数据了 所以要回到上一页显示数据
  if (employeeList.value.length === 1 && pageParam.value.page !== 1) {
    pageParam.value.page--;
  }
  getEmployeeList();
};
// 添加员工事件
const addEmployeeClick = () => {
  // router.push("/main/employee/detail");
  router.push({ name: "employeeDetail", query: { id: 0 } });
  // const res = router.getRoutes(); // 获取路由列表信息函数
  // console.log(res);
};

// 给员工分配角色事件
const addRole = async (id) => {
  // 获取角色列表数据
  const res = await getEnabledRoleListApi();
  roleListData.value = res;
  //记录当前员工id
  currenId.value = id;
  // console.log(res, "角色列表数据");
  //获取员工已有角色id列表合集
  const { roleIds } = await getEmployeeDetailApi(id);
  checkListRoleIds.value = roleIds;
  // console.log(roleIds, "员工已有角色合集");
  //获取角色详情数据
  RoleDialogVisible.value = true;
};

// 分配员工角色确定按钮事件
const assignRolesBtn = async () => {
  try {
    const id = currenId.value;
    const roleIds = checkListRoleIds.value;
    await assignRolesApi({ id, roleIds });
    ElMessage.success("分配角色成功");
    setTimeout(() => {
      getEmployeeList();
    }, 500);
  } catch (error) {
    ElMessage.error("分配角色失败");
  } finally {
    RoleDialogVisible.value = false;
  }
};

// 关闭分配角色对话框事件
const closeBtn = () => {
  RoleDialogVisible.value = false;
};

// 页码展示条数改变事件
const handleSizeChange = (val) => {
  pageParam.value.pagesize = val;
  getEmployeeList();
};
// 当前页码改变事件
const handleCurrentChange = (val) => {
  pageParam.value.page = val;
  getEmployeeList();
};
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
  .left-container {
    width: 280px;
    border-right: 1px solid #eaeef4;
    padding-right: 20px;
  }
  .right-container {
    flex: 1;
    padding: 20px;
    padding-right: 0px;
    .operate-tools {
      margin-top: -20px;
      margin-bottom: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      color: #fff;
      background: pink;
      border-radius: 50%;
      font-size: 15px;
      display: inline-block;
    }
    .el-pagination {
      margin-top: 20px;
    }
  }
}
</style>
